package com.xbongbong.paas.script.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.pojo.dto.FixDataJobDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.ShowTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.script.help.InitExplainsHelper;
import com.xbongbong.saas.script.tempenum.TempProductEnum;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.CompanyModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/script/multi/unit")
public class MultiUnitScriptController {
    private static final Logger LOG = LoggerFactory.getLogger(MultiUnitScriptController.class);

    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private CompanyModel companyModel;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;


    @RequestMapping(value = "/addProductExplain", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String addProductExplain(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        long start = DateTimeUtil.getInt();
        LocaleContextHolder.setLocale(Locale.CHINA);
        List<String> corpidList = fixDataJobDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            corpidList = companyModel.getCorpidList();
        }
        LOG.warn("数据库中共有公司" + corpidList.size() + "家");
        int corpidCount = 0;

        List<FieldAttrEntity> fieldAttrList = new ArrayList<>();
        List<String> enumAttrs = InitExplainsHelper.getBusinessEnumAttrs(ProductEnum.class);
        List objs = Arrays.asList(ProductEnum.ENABLE_MULTI_UNIT);

        for (Object obj : objs) {
            FieldAttrEntity newFieldAttrEntity = InitExplainsHelper.setField(ProductEnum.class, enumAttrs, obj);
            try {
                Method method = TempProductEnum.class.getMethod("init" + newFieldAttrEntity.getSaasAttr().substring(0, 1).toUpperCase() + newFieldAttrEntity.getSaasAttr().substring(1), FieldAttrEntity.class);
                method.invoke(TempProductEnum.class, newFieldAttrEntity);
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
            newFieldAttrEntity.setIsRedundant(0);
            fieldAttrList.add(newFieldAttrEntity);
        }

        HashSet<String> attrList = new HashSet<>();
        for (FieldAttrEntity fieldAttrEntity : fieldAttrList) {
            attrList.add(fieldAttrEntity.getAttr());
        }
        for (String corpid : corpidList) {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put(ParameterConstant.CORPID, corpid);
            param.put("businessType", XbbRefTypeEnum.PRODUCT.getCode());
            List<PaasFormExplainEntity> entitys = paasFormExplainModel.getNoHandleExplainsByFindEntitys(param);
            for (PaasFormExplainEntity entity : entitys){
                if (Objects.equals("[]", entity.getExplains())) {
                    continue;
                }
                boolean canInsert = true;
                List<FieldAttrEntity> fieldAttrEntityList = JSONArray.parseArray(entity.getExplains(),FieldAttrEntity.class);

                int obj = 0;
                for(int i = 0; i < fieldAttrEntityList.size(); i++){

                    FieldAttrEntity fieldAttrEntity = fieldAttrEntityList.get(i);
                    //插入到当前字段后面
                    if (Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.UNIT.getAttr())) {
                        obj = i + 1 ;
                        fieldAttrEntity.setSaasAttr(ProductEnum.UNIT.getSaasAttr());
                    }
                    if (attrList.contains(fieldAttrEntity.getAttr())) {
                        canInsert = false;
                        LOG.warn(corpid + "该公司已经存在" + fieldAttrEntity.getAttr() + "字段");
                        break;
                    }
                }
                if (canInsert && obj != 0) {
                    for (int i = 0; i < fieldAttrList.size(); i++) {
                        FieldAttrEntity fieldAttrEntity = fieldAttrList.get(i);
                        fieldAttrEntityList.add(obj + i , fieldAttrEntity);
                    }
                    String explains = JSONObject.toJSONString(fieldAttrEntityList);
                    entity.setExplains(explains);
                    paasFormExplainModel.update(entity);
                }else {
                    String explains = JSONObject.toJSONString(fieldAttrEntityList);
                    entity.setExplains(explains);
                    paasFormExplainModel.update(entity);
                }
            }
            ++ corpidCount;
            LOG.warn("公司" + corpidCount + "/" + corpidList.size() + "/" +corpid);
        }

        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        LOG.warn("操作成功");
        return null;
    }

    @RequestMapping(value = "/rollBackProductExplain", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String rollBackProductExplain(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        long start = DateTimeUtil.getInt();
        LocaleContextHolder.setLocale(Locale.CHINA);
        List<String> corpidList = fixDataJobDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            corpidList = companyModel.getCorpidList();
        }
        LOG.warn("数据库中共有公司" + corpidList.size() + "家");
        int corpidCount = 0;
        for (String corpid : corpidList) {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put(ParameterConstant.CORPID, corpid);
            param.put("businessType", XbbRefTypeEnum.PRODUCT.getCode());
            List<PaasFormExplainEntity> entitys = paasFormExplainModel.getNoHandleExplainsByFindEntitys(param);
            for (PaasFormExplainEntity entity : entitys){
                if (Objects.equals("[]", entity.getExplains())) {
                    continue;
                }
                List<FieldAttrEntity> fieldAttrEntityList = JSONArray.parseArray(entity.getExplains(),FieldAttrEntity.class);
                for(FieldAttrEntity fieldAttrEntity : fieldAttrEntityList){
                    if (Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.UNIT.getAttr())) {
                        fieldAttrEntity.setSaasAttr(SelectProductEnum.UNIT.getSaasAttr());
                    } else if (Objects.equals(fieldAttrEntity.getSaasAttr(), ProductEnum.ENABLE_MULTI_UNIT.getSaasAttr())) {
                        fieldAttrEntity.setShowType(ShowTypeEnum.NONE.getCode());
                        fieldAttrEntity.setEditHide(1);
                    }
                }
                entity.setExplains(JSONObject.toJSONString(fieldAttrEntityList));
                paasFormExplainModel.update(entity);
            }
            ++ corpidCount;
            LOG.warn("公司" + corpidCount + "/" + corpidList.size() + "/" +corpid);
        }

        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        LOG.warn("操作成功");
        return null;
    }

}
